﻿using System;
using System.ServiceModel;
using MugenInjection.Wcf.Interface;

namespace MugenInjection.Wcf.Config
{
    /// <summary>
    /// Represents the dispose instance behavior.
    /// </summary>
    public class DisposeReleaseInstanceBehavior : IReleaseInstanceBehavior
    {
        #region Implementation of IReleaseInstanceBehavior

        /// <summary>
        /// Called when an <see cref="T:System.ServiceModel.InstanceContext"/> object recycles a service object.
        /// </summary>
        /// <param name="instanceContext">The service's instance context.</param><param name="instance">The service object to be recycled.</param>
        public void Release(InstanceContext instanceContext, object instance)
        {
            if (instance == null) return;
            bool singleton = WcfConfigExtension.IsServiceSingleton(instance.GetType());
            if (singleton) return;
            var disposable = instance as IDisposable;
            if (disposable != null)
                disposable.Dispose();
        }

        #endregion
    }
}